<template>
    <el-main class="main-container">
        <!-- 1. 头部 -->
        <div class="header-wrapper">
            <div class="page-title">
                <h1>店铺管理</h1>
                <p>管理所有店铺信息和状态</p>
            </div>
            <div class="user-profile">
                <el-dropdown trigger="hover" @command="handleDropdownCommand">
                    <div class="avatar-wrapper">
                        <el-badge :value="onlineStoreCount" :max="99" :hidden="!onlineStoreCount">
                            <el-avatar class="user-avatar" :src="$store.state.user.headPicture"
                                @error="handleAvatarError">
                                <i class="el-icon-user-solid"></i>
                            </el-avatar>
                        </el-badge>
                        <div class="user-info">
                            <span class="user-name">{{ $store.state.user.name || '管理员' }}</span>
                            <span class="user-role">系统管理员</span>
                        </div>
                        <i class="el-icon-arrow-down dropdown-icon"></i>
                    </div>
                    <el-dropdown-menu slot="dropdown" class="custom-dropdown">
                        <el-dropdown-item command="profile" icon="el-icon-user">个人资料</el-dropdown-item>
                        <el-dropdown-item command="upload" icon="el-icon-camera">更换头像</el-dropdown-item>
                        <el-dropdown-item command="settings" icon="el-icon-setting">系统设置</el-dropdown-item>
                        <el-dropdown-item divided command="logout" icon="el-icon-switch-button">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>

        <!-- 2. 统计卡片 -->
        <div class="stats-section">
            <div class="stat-card">
                <div class="stat-icon total"><i class="el-icon-s-shop"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ total }}</div>
                    <div class="stat-label">总店铺数</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon active"><i class="el-icon-check"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ activeStoreCount }}</div>
                    <div class="stat-label">运营中</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon inactive"><i class="el-icon-close"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ inactiveStoreCount }}</div>
                    <div class="stat-label">已停业</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon online"><i class="el-icon-connection"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ onlineStoreCount }}</div>
                    <div class="stat-label">在线店铺</div>
                </div>
            </div>
        </div>

        <!-- 3. 搜索 & 操作栏 -->
        <div class="action-section">
            <div class="search-filters">
                <!-- 搜索类型 -->
                <el-select v-model="searchType" placeholder="搜索类型" class="search-type-select">
                    <el-option label="店铺名称" value="STORE_NAME"></el-option>
                    <el-option label="店主姓名" value="BOSS_NAME"></el-option>
                    <el-option label="联系电话" value="MOBILE_PHONE"></el-option>
                </el-select>

                <!-- 搜索输入框 -->
                <el-input v-model="searchValue" placeholder="请输入搜索内容..." clearable class="search-input"
                    @clear="handleClear" @keyup.enter.native="handleSearch">
                    <i slot="prefix" class="el-icon-search"></i>
                </el-input>

                <!-- 状态筛选 -->
                <el-select v-model="filters.status" placeholder="选择状态" clearable class="filter-select">
                    <el-option label="全部状态" value=""></el-option>
                    <el-option label="运营中" :value="1"></el-option>
                    <el-option label="已停业" :value="0"></el-option>
                </el-select>

                <!-- 分类筛选 -->
                <el-select v-model="filters.storeType" placeholder="店铺分类" clearable class="filter-select">
                    <el-option label="全部分类" :value="null"></el-option>
                    <el-option v-for="item in storeTypeOptions" :key="item.id" :label="item.storeType"
                        :value="item.storeIntType">
                    </el-option>
                </el-select>

                <!-- 评分区间 -->
                <div class="rating-range-wrapper">
                    <span class="range-label">评分范围</span>
                    <el-input-number v-model="filters.minRating" :min="0" :max="5" :step="0.1" :precision="1"
                        size="small" placeholder="最低" class="rating-input" controls-position="right" />
                    <span class="range-separator">~</span>
                    <el-input-number v-model="filters.maxRating" :min="0" :max="5" :step="0.1" :precision="1"
                        size="small" placeholder="最高" class="rating-input" controls-position="right" />
                </div>

                <!-- 按钮 -->
                <el-button type="primary" icon="el-icon-search" @click="handleSearch"
                    :loading="listLoading">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
            </div>

            <div class="action-buttons">
                <el-button type="success" icon="el-icon-plus" @click="handleAdd">添加店铺</el-button>
                <el-button type="danger" icon="el-icon-delete" :disabled="!multipleSelection.length"
                    @click="handleBatchDelete">
                    批量删除 ({{ multipleSelection.length }})
                </el-button>
                <el-button type="info" icon="el-icon-download" @click="handleExport">导出数据</el-button>
            </div>
        </div>

        <!-- 4. 表格 -->
        <div class="table-section">
            <el-table v-loading="listLoading" :data="tableData" stripe
                :header-cell-style="{ background: '#fafafa', color: '#606266' }"
                @selection-change="handleSelectionChange" @row-click="handleRowClick">

                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="id" label="店铺ID" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag size="small" type="info">#{{ row.id }}</el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="店铺图片" width="90" align="center">
                    <template #default="{ row }">
                        <div class="store-image-cell">
                            <el-image :src="row.image || '/placeholder-store.jpg'" class="store-image" fit="cover"
                                :preview-src-list="[row.image || '/placeholder-store.jpg']">
                                <div slot="error" class="image-slot"><i class="el-icon-s-shop"></i></div>
                            </el-image>
                            <div v-if="row.isOnline" class="online-indicator"></div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="name" label="店铺名称" min-width="180" show-overflow-tooltip>
                    <template #default="{ row }">
                        <div class="store-name-cell">
                            <span class="store-name">{{ row.name }}</span>
                            <div class="store-tags">
                                <el-tag v-if="row.isFeatured" size="mini" type="warning">推荐</el-tag>
                                <el-tag v-if="row.isNew" size="mini" type="success">新店</el-tag>
                                <el-tag v-if="row.isHot" size="mini" type="danger">热门</el-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="storeType" label="店铺分类" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag size="small">{{ getStoreTypeText(row.storeType) }}</el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="owner" label="店主" width="120" align="center">
                    <template #default="{ row }">
                        <div class="owner-cell">
                            <el-avatar :src="row.ownerAvatar" :size="30"><i class="el-icon-user-solid"></i></el-avatar>
                            <span class="owner-name">{{ row.owner }}</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="phone" label="联系电话" width="130" align="center">
                    <template #default="{ row }"><span>{{ formatPhone(row.phone) }}</span></template>
                </el-table-column>

                <el-table-column prop="rating" label="评分" width="130" align="center">
                    <template #default="{ row }">
                        <div class="rating-cell">
                            <el-rate v-model="row.rating" disabled
                                :colors="['#F56C6C', '#E6A23C', '#67C23A']"></el-rate>
                            <span class="rating-text">{{ row.rating || 0 }}</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="status" label="状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" :active-value="1" :inactive-value="0" active-color="#13ce66"
                            inactive-color="#ff4949" @click.native.stop
                            @change="handleStatusChange(row.id, row.status)" />
                    </template>
                </el-table-column>

                <el-table-column prop="createTime" label="创建时间" width="160" align="center">
                    <template #default="{ row }"><span>{{ formatDate(row.createTime) }}</span></template>
                </el-table-column>

                <el-table-column label="操作" width="220" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-tooltip content="查看详情" placement="top">
                            <el-button size="mini" type="info" icon="el-icon-view" circle
                                @click.stop="handleView(row)" />
                        </el-tooltip>
                        <el-tooltip content="编辑" placement="top">
                            <el-button size="mini" type="primary" icon="el-icon-edit" circle
                                @click.stop="handleEdit(row)" />
                        </el-tooltip>
                        <el-tooltip content="商品管理" placement="top">
                            <el-button size="mini" type="success" icon="el-icon-s-goods" circle
                                @click.stop="handleGoods(row)" />
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button size="mini" type="danger" icon="el-icon-delete" circle
                                @click.stop="handleDelete(row)" />
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 5. 分页 -->
        <div class="pagination-section">
            <div class="pagination-info">共 {{ total }} 条，每页 {{ pageSize }} 条</div>
            <el-pagination background :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]"
                :page-size.sync="pageSize" :total="total" layout="sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handlePageChange">
            </el-pagination>
        </div>

        <!-- 6. 添加/编辑弹窗 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" :before-close="handleDialogClose"
            :close-on-click-modal="false" custom-class="store-dialog">
            <el-form :model="storeForm" :rules="formRules" ref="storeFormRef" label-width="100px" class="store-form">
                <div class="form-section">
                    <h3 class="section-title">基本信息</h3>
                    <el-form-item label="店铺名称" prop="name">
                        <el-input v-model="storeForm.name" placeholder="请输入店铺名称" clearable></el-input>
                    </el-form-item>

                    <el-form-item label="店铺分类" prop="storeType">
                        <el-select v-model="storeForm.storeType" placeholder="请选择分类" style="width:100%">
                            <el-option v-for="item in storeTypeOptions" :key="item.id" :label="item.storeType"
                                :value="item.storeType">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="店主姓名" prop="owner">
                                <el-input v-model="storeForm.owner" placeholder="请输入店主姓名" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话" prop="phone">
                                <el-input v-model="storeForm.phone" placeholder="请输入联系电话" clearable>
                                    <i slot="prefix" class="el-icon-phone"></i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="电子邮箱" prop="email">
                        <el-input v-model="storeForm.email" placeholder="请输入电子邮箱" clearable>
                            <i slot="prefix" class="el-icon-message"></i>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="店铺地址" prop="address">
                        <el-input v-model="storeForm.address" placeholder="请输入详细地址" clearable>
                            <i slot="prefix" class="el-icon-location"></i>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="店铺简介">
                        <el-input type="textarea" v-model="storeForm.description" :rows="4"
                            placeholder="请输入店铺简介（选填）"></el-input>
                    </el-form-item>
                </div>

                <div class="form-section">
                    <h3 class="section-title">店铺图片</h3>
                    <el-form-item label="店铺图片">
                        <el-upload class="store-uploader" action="#" :show-file-list="false"
                            :before-upload="handleBeforeUpload" :http-request="handleUploadImage" accept="image/*">
                            <img v-if="storeForm.imageUrl" :src="storeForm.imageUrl" class="store-image-preview">
                            <div v-else class="upload-placeholder">
                                <i class="el-icon-plus upload-icon"></i>
                                <div class="upload-text">点击上传图片</div>
                                <div class="upload-tip">支持 JPG、PNG，最大 2MB</div>
                            </div>
                        </el-upload>
                    </el-form-item>
                </div>

                <div class="form-section">
                    <h3 class="section-title">店铺设置</h3>
                    <el-form-item label="推荐店铺">
                        <el-switch v-model="storeForm.isFeatured" active-color="#f39c12"></el-switch>
                        <span class="setting-desc">标记为推荐店铺，在首页展示</span>
                    </el-form-item>
                    <el-form-item label="新店标识">
                        <el-switch v-model="storeForm.isNew" active-color="#67c23a"></el-switch>
                        <span class="setting-desc">显示"新店"标签</span>
                    </el-form-item>
                    <el-form-item label="热门店铺">
                        <el-switch v-model="storeForm.isHot" active-color="#f56c6c"></el-switch>
                        <span class="setting-desc">显示"热门"标签</span>
                    </el-form-item>
                    <el-form-item label="营业状态">
                        <el-switch v-model="storeForm.status" :active-value="1" :inactive-value="0"
                            active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                        <span class="setting-desc">{{ storeForm.status === 1 ? '营业中' : '已停业' }}</span>
                    </el-form-item>
                </div>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handleDialogClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmitForm" :loading="submitLoading">
                    {{ isEdit ? '保存修改' : '立即创建' }}
                </el-button>
            </span>
        </el-dialog>

        <!-- 7. 详情弹窗 -->
        <el-dialog title="店铺详情" :visible.sync="detailDialogVisible" width="700px"
            :before-close="() => detailDialogVisible = false">
            <div v-if="currentStore" class="store-detail">
                <div class="detail-header">
                    <div class="detail-image">
                        <el-image :src="currentStore.image || '/placeholder-store.jpg'" class="detail-store-image"
                            fit="cover">
                            <div slot="error" class="image-slot"><i class="el-icon-s-shop"></i></div>
                        </el-image>
                        <div v-if="currentStore.isOnline" class="online-badge">营业中</div>
                    </div>
                    <div class="detail-info">
                        <h3>{{ currentStore.name }}</h3>
                        <p class="store-storeType">{{ getStoreTypeText(currentStore.storeType) }}</p>
                        <div class="store-status-tags">
                            <el-tag :type="getStatusType(currentStore.status)">
                                {{ getStatusText(currentStore.status) }}
                            </el-tag>
                            <el-tag v-if="currentStore.isFeatured" type="warning">推荐店铺</el-tag>
                        </div>
                        <div class="rating-display">
                            <el-rate v-model="currentStore.rating" disabled></el-rate>
                            <span>{{ currentStore.rating || 0 }} 分</span>
                        </div>
                    </div>
                </div>
                <el-divider></el-divider>
                <div class="detail-content">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <p><strong>店主：</strong>{{ currentStore.owner }}</p>
                            <p><strong>联系电话：</strong>{{ currentStore.phone }}</p>
                            <p><strong>店铺地址：</strong>{{ currentStore.address || '未设置' }}</p>
                        </el-col>
                        <el-col :span="12">
                            <p><strong>创建时间：</strong>{{ formatDate(currentStore.createTime) }}</p>
                            <p><strong>商品数量：</strong>{{ currentStore.goodsCount || 0 }}</p>
                            <p><strong>月销售额：</strong>¥{{ currentStore.monthlySales || '0.00' }}</p>
                        </el-col>
                    </el-row>
                    <div v-if="currentStore.description" class="store-description">
                        <p><strong>店铺简介：</strong></p>
                        <p>{{ currentStore.description }}</p>
                    </div>
                </div>
            </div>
            <span slot="footer">
                <el-button @click="detailDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="handleEdit(currentStore)">编辑店铺</el-button>
                <el-button type="success" @click="handleGoods(currentStore)">商品管理</el-button>
            </span>
        </el-dialog>
    </el-main>
</template>

<script>
import { setStoreId, batchDelete, updateStore, getStoreType, updateStoreStatus, getlist, AddStore, GetByImportanceKey } from '@/api/admin/store.js'
import { upload } from '@/api/common/common'

export default {
    name: 'StoreManagement',
    data() {
        return {
            filters: {
                status: '',
                storeType: null,
                minRating: null,
                maxRating: null
            },
            searchType: { value: 'STORE_NAME' },// 对象形式
            searchValue: '',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            listLoading: false,
            tableData: [],
            multipleSelection: [],
            detailDialogVisible: false,
            currentStore: null,
            onlineStoreCount: 0,
            isSearching: false, // 标识是否在搜索模式

            dialogVisible: false,
            isEdit: false,
            submitLoading: false,
            storeForm: {
                id: null,
                name: '',
                storeType: '',
                owner: '',
                phone: '',
                email: '',
                address: '',
                description: '',
                imageUrl: '',
                isFeatured: false,
                isNew: false,
                isHot: false,
                status: 1
            },
            storeTypeOptions: [],
            formRules: {
                name: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
                storeType: [{ required: true, message: '请选择店铺分类', trigger: 'change' }],
                owner: [{ required: true, message: '请输入店主姓名', trigger: 'blur' }],
                phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
                address: [{ required: true, message: '请输入店铺地址', trigger: 'blur' }]
            }
        }
    },
    computed: {
        dialogTitle() { return this.isEdit ? '编辑店铺' : '添加新店铺' },
        activeStoreCount() { return this.tableData.filter(i => i.status === 1).length },
        inactiveStoreCount() { return this.tableData.filter(i => i.status === 0).length }
    },
    methods: {
        handleClear() {
            this.searchValue = ''
            this.isSearching = false
            this.currentPage = 1
            this.loadData()
        },

        formatPhone(phone) {
            return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '未设置'
        },

        formatDate(date) {
            return date ? new Date(date).toLocaleString('zh-CN') : '-'
        },

        getStatusText(status) {
            return status === 0 ? '已停业' : '运营中'
        },

        getStatusType(status) {
            return status === 0 ? 'danger' : 'success'
        },

        getStoreTypeText(intType) {
            const found = this.storeTypeOptions.find(t => t.storeIntType === intType)
            return found ? found.storeType : '未知分类'
        },

        handleSelectionChange(val) {
            this.multipleSelection = val
        },

        handleRowClick(row, column, event) {
            const isCheckbox = event.target.classList.contains('el-checkbox__inner')
            const isButton = event.target.tagName === 'BUTTON'
            if (!isCheckbox && !isButton && column.property !== 'selection') {
                this.handleGoods(row)
            }
        },

        async handlePageChange(p) {
            this.currentPage = p
            if (this.isSearching) {
                await this.handleSearch()
            } else {
                await this.loadData()
            }
        },

        async handleSizeChange(s) {
            this.pageSize = s
            this.currentPage = 1
            if (this.isSearching) {
                await this.handleSearch()
            } else {
                await this.loadData()
            }
        },

        async handleSearch() {
            console.log('🔍 搜索类型:', this.searchType)
            console.log('🔍 搜索内容:', this.searchValue)
            console.log('🔍 筛选条件:', this.filters)

            this.listLoading = true

            try {
                // 如果搜索内容为空，退出搜索模式
                if (!this.searchValue.trim()) {
                    this.isSearching = false
                    this.currentPage = 1
                    await this.loadData()
                    return
                }

                // 进入搜索模式
                this.isSearching = true

                const params = {
                    imformationWord: this.searchValue.trim(),
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    searchType: this.searchType
                }

                // 添加筛选条件（非空才添加）
                if (this.filters.status !== '') {
                    params.status = this.filters.status
                }
                if (this.filters.storeType !== null) {
                    params.storeType = this.filters.storeType
                }
                if (this.filters.minRating !== null) {
                    params.minRating = this.filters.minRating
                }
                if (this.filters.maxRating !== null) {
                    params.maxRating = this.filters.maxRating
                }

                console.log('📤 搜索参数:', params)

                const res = await GetByImportanceKey(params)

                console.log('📥 搜索响应:', res)

                if (res && res.data) {
                    // 根据实际返回结构调整
                    if (res.data.code === 1 && res.data.data) {
                        this.tableData = res.data.data.records || []
                        this.total = res.data.data.total || 0
                    } else if (res.data.records) {
                        // 直接返回 records 的情况
                        this.tableData = res.data.records || []
                        this.total = res.data.total || 0
                    } else {
                        this.tableData = []
                        this.total = 0
                    }

                    if (this.tableData.length === 0) {
                        this.$message.info('未找到相关店铺')
                    } else {
                        this.$message.success(`找到 ${this.total} 个店铺`)
                    }
                } else {
                    this.tableData = []
                    this.total = 0
                    this.$message.warning('搜索结果为空')
                }

            } catch (error) {
                console.error("❌ 搜索失败:", error)
                this.$message.error(error.message || '搜索失败，请稍后重试')
                this.tableData = []
                this.total = 0
            } finally {
                this.listLoading = false
            }
        },

        async handleRefresh() {
            this.filters = { status: '', storeType: null, minRating: null, maxRating: null }
            this.searchValue = ''
            this.searchType = 'NAME'
            this.isSearching = false
            this.currentPage = 1
            await this.loadData()
            this.$message.success('已重置')
        },

        handleAdd() {
            this.isEdit = false
            this.resetForm()
            this.dialogVisible = true
        },

        handleEdit(row) {
            this.isEdit = true
            const typeItem = this.storeTypeOptions.find(t => t.storeIntType === row.storeType)
            this.storeForm = {
                ...row,
                storeType: typeItem ? typeItem.storeType : '',
                imageUrl: row.image || ''
            }
            this.dialogVisible = true
        },

        handleView(row) {
            this.currentStore = row
            this.detailDialogVisible = true
        },

        handleGoods(row) {
            const storeId = row.id
            setStoreId(row.id)
            localStorage.setItem('StoreName', row.name)
            this.$router.push(`/home/Goods/${storeId}`)

        },

        handleDialogClose() {
            this.$confirm('确认关闭？', '提示', { type: 'warning' })
                .then(() => {
                    this.dialogVisible = false
                    this.resetForm()
                })
                .catch(() => { })
        },

        resetForm() {
            this.storeForm = {
                id: null,
                name: '',
                storeType: '',
                owner: '',
                phone: '',
                email: '',
                address: '',
                description: '',
                imageUrl: '',
                isFeatured: false,
                isNew: false,
                isHot: false,
                status: 1
            }
            this.$nextTick(() => this.$refs.storeFormRef?.clearValidate())
        },

        handleBeforeUpload(file) {
            const isImg = file.type.startsWith('image/')
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isImg) {
                this.$message.error('只能上传图片格式')
                return false
            }
            if (!isLt2M) {
                this.$message.error('图片大小不能超过 2MB')
                return false
            }
            return true
        },

        async handleUploadImage(param) {
            try {
                const fd = new FormData()
                fd.append('file', param.file)
                const res = await upload(fd)
                this.storeForm.imageUrl = res
                this.$message.success('上传成功')
            } catch (error) {
                console.error('上传失败:', error)
                this.$message.error('上传失败')
            }
        },

        handleSubmitForm() {
            this.$refs.storeFormRef.validate(async valid => {
                if (!valid) {
                    this.$message.warning('请填写完整信息')
                    return
                }

                try {
                    this.submitLoading = true

                    // 把文字转换成 storeIntType
                    const typeItem = this.storeTypeOptions.find(
                        item => item.storeType === this.storeForm.storeType
                    )

                    if (!typeItem) {
                        this.$message.error('无效的店铺分类')
                        return
                    }

                    const postData = {
                        ...this.storeForm,
                        storeType: typeItem.storeIntType,
                        image: this.storeForm.imageUrl
                    }

                    console.log('📤 提交数据:', postData)

                    if (this.isEdit) {
                        await updateStore(postData)
                        this.$message.success('更新成功')
                    } else {
                        const res = await AddStore(postData)
                        if (res.data.code === 1) {
                            this.$message.success('添加成功')
                        } else {
                            throw new Error(res.data.msg || '添加失败')
                        }
                    }

                    this.dialogVisible = false
                    this.resetForm()
                    await this.loadData()

                } catch (err) {
                    console.error('❌ 提交错误:', err)
                    this.$message.error(err.message || (this.isEdit ? '更新失败' : '添加失败'))
                } finally {
                    this.submitLoading = false
                }
            })
        },

        async handleBatchDelete() {
            if (!this.multipleSelection.length) {
                this.$message.warning('请选择要删除的店铺')
                return
            }

            try {
                await this.$confirm(`确定删除 ${this.multipleSelection.length} 个店铺？`, '警告', {
                    type: 'warning',
                    confirmButtonText: '确定删除',
                    cancelButtonText: '取消'
                })

                const ids = this.multipleSelection.map(i => i.id)
                await batchDelete(ids)
                this.$message.success('删除成功')
                this.multipleSelection = []

                // 如果删除后当前页没数据了，回到上一页
                if (this.tableData.length === ids.length && this.currentPage > 1) {
                    this.currentPage--
                }

                await this.loadData()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败')
                }
            }
        },

        async handleDelete(row) {
            try {
                await this.$confirm('确定删除该店铺？', '警告', {
                    type: 'warning',
                    confirmButtonText: '确定删除',
                    cancelButtonText: '取消'
                })

                await batchDelete([row.id])
                this.$message.success('删除成功')

                // 如果删除后当前页没数据了，回到上一页
                if (this.tableData.length === 1 && this.currentPage > 1) {
                    this.currentPage--
                }

                await this.loadData()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败')
                }
            }
        },

        async handleStatusChange(id, status) {
            try {
                const res = await updateStoreStatus(id, status)
                if (res.data.code === 1) {
                    this.$message.success('状态更新成功')
                    // 不重新加载，保持当前页
                } else {
                    throw new Error('更新失败')
                }
            } catch (error) {
                // 恢复原状态
                const item = this.tableData.find(i => i.id === id)
                if (item) {
                    item.status = status === 1 ? 0 : 1
                }
                console.error('状态更新失败:', error)
                this.$message.error('状态更新失败')
            }
        },

        handleExport() {
            this.$message.info('导出功能开发中...')
        },

        handleDropdownCommand(cmd) {
            const actions = {
                profile: () => this.$message.info('个人资料功能开发中...'),
                upload: () => this.$message.info('更换头像功能开发中...'),
                settings: () => this.$message.info('系统设置功能开发中...'),
                logout: () => this.handleLogout()
            }
            actions[cmd]?.()
        },

        async handleLogout() {
            try {
                await this.$confirm('确定退出登录？', '提示', { type: 'warning' })
                this.$store.dispatch('user/logout')
                this.$router.push('/')
            } catch (error) {
                // 取消退出
            }
        },

        handleAvatarError() {
            this.$store.commit('user/UPDATE_AVATAR', '/default-avatar.png')
        },

        async loadData() {
            this.listLoading = true

            try {
                console.log('📥 加载数据，当前页:', this.currentPage, '每页:', this.pageSize)

                // 方式1: 如果你的 getlist 只接收页码
                const res = await getlist(this.currentPage)

                // 方式2: 如果需要传对象参数，用这个
                // const res = await getlist({
                //     currentPage: this.currentPage,
                //     pageSize: this.pageSize
                // })

                console.log('📥 接口返回:', res)

                // 根据实际返回结构调整
                if (res && res.data) {
                    if (res.data.code === 1 && res.data.data) {
                        // 格式1: {code: 1, data: {records: [], total: 100}}
                        this.tableData = res.data.data.records || []
                        this.total = res.data.data.total || 0
                    } else if (res.data.records) {
                        // 格式2: {records: [], total: 100}
                        this.tableData = res.data.records || []
                        this.total = res.data.total || 0
                    } else {
                        // 格式3: 直接是数组
                        this.tableData = Array.isArray(res.data) ? res.data : []
                        this.total = this.tableData.length
                    }

                    console.log('✅ 加载成功，数据量:', this.tableData.length)
                } else {
                    console.warn('⚠️ 返回数据格式异常:', res)
                    this.tableData = []
                    this.total = 0
                }
            } catch (err) {
                console.error('❌ 加载失败:', err)
                console.error('错误详情:', {
                    message: err.message,
                    response: err.response,
                    stack: err.stack
                })

                this.$message.error('加载数据失败: ' + (err.message || '未知错误'))
                this.tableData = []
                this.total = 0
            } finally {
                this.listLoading = false
            }
        },

        // 加载店铺分类
        async loadStoreTypes() {
            try {
                console.log('📥 加载店铺分类...')
                const res = await getStoreType()
                console.log('📥 分类数据:', res)

                if (res && res.data) {
                    if (res.data.code === 1 && res.data.data) {
                        this.storeTypeOptions = res.data.data || []
                    } else if (Array.isArray(res.data)) {
                        this.storeTypeOptions = res.data || []
                    } else {
                        this.storeTypeOptions = []
                    }

                    console.log('✅ 分类加载成功:', this.storeTypeOptions)

                    // 设置默认值
                    if (this.storeTypeOptions.length > 0 && !this.storeForm.storeType) {
                        this.storeForm.storeType = this.storeTypeOptions[0].storeType
                    }
                } else {
                    this.storeTypeOptions = []
                }
            } catch (err) {
                console.error('❌ 加载店铺分类失败:', err)
                this.$message.error('加载店铺分类失败')
                this.storeTypeOptions = []
            }
        }
    },

    async mounted() {
        console.log('🚀 组件挂载，开始初始化...')

        // 加载店铺列表
        await this.loadData()

        // 加载店铺分类
        await this.loadStoreTypes()

        console.log('✅ 初始化完成')
    }
}
</script>

<style scoped>
/* 主容器 */
.main-container {
    padding: 24px;
    background: #f5f7fa;
    min-height: 100vh;
}

/* 头部样式 */
.header-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.page-title h1 {
    margin: 0;
    font-size: 24px;
    color: #303133;
}

.page-title p {
    margin: 8px 0 0;
    color: #909399;
    font-size: 14px;
}

.user-profile .avatar-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 8px;
    transition: all 0.3s;
}

.user-profile .avatar-wrapper:hover {
    background: #f5f7fa;
}

.user-info {
    display: flex;
    flex-direction: column;
}

.user-name {
    font-weight: 500;
    color: #303133;
}

.user-role {
    font-size: 12px;
    color: #909399;
}

/* 统计卡片 */
.stats-section {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}

.stat-card {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    font-size: 24px;
    color: white;
}

.stat-icon.total {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.inactive {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.online {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
}

.stat-label {
    margin-top: 4px;
    color: #909399;
    font-size: 14px;
}

/* 搜索操作栏 */
.action-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    flex-wrap: wrap;
    gap: 12px;
}

.search-filters {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    flex: 1;
    align-items: center;
}

.search-type-select {
    width: 120px;
}

.search-input {
    width: 240px;
}

.filter-select {
    width: 140px;
}

.rating-range-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 0 12px;
    background: #f5f7fa;
    border-radius: 4px;
}

.range-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

.rating-input {
    width: 80px;
}

.range-separator {
    color: #909399;
}

.action-buttons {
    display: flex;
    gap: 12px;
}

/* 表格样式 */
.table-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
}

.store-image-cell {
    position: relative;
    display: inline-block;
}

.store-image {
    width: 60px;
    height: 60px;
    border-radius: 8px;
}

.online-indicator {
    position: absolute;
    top: 2px;
    right: 2px;
    width: 10px;
    height: 10px;
    background: #67c23a;
    border: 2px solid white;
    border-radius: 50%;
}

.store-name-cell {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.store-name {
    font-weight: 500;
    color: #303133;
}

.store-tags {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}

.owner-cell {
    display: flex;
    align-items: center;
    gap: 8px;
    justify-content: center;
}

.owner-name {
    font-size: 14px;
}

.rating-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.rating-text {
    font-weight: 500;
    color: #f39c12;
}

/* 分页样式 */
.pagination-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 弹窗样式 */
.store-form .form-section {
    margin-bottom: 24px;
}

.section-title {
    margin: 0 0 16px;
    padding-bottom: 12px;
    border-bottom: 2px solid #f0f0f0;
    font-size: 16px;
    color: #303133;
}

.store-uploader {
    width: 100%;
}

.store-image-preview {
    width: 100%;
    max-height: 300px;
    object-fit: cover;
    border-radius: 8px;
    cursor: pointer;
}

.upload-placeholder {
    width: 100%;
    height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
}

.upload-placeholder:hover {
    border-color: #409eff;
    background: #f5f7fa;
}

.upload-icon {
    font-size: 48px;
    color: #c0c4cc;
}

.upload-text {
    margin-top: 12px;
    font-size: 14px;
    color: #606266;
}

.upload-tip {
    margin-top: 4px;
    font-size: 12px;
    color: #909399;
}

.setting-desc {
    margin-left: 12px;
    font-size: 13px;
    color: #909399;
}

/* 详情弹窗 */
.store-detail {
    padding: 0;
}

.detail-header {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
}

.detail-image {
    position: relative;
    flex-shrink: 0;
}

.detail-store-image {
    width: 200px;
    height: 200px;
    border-radius: 12px;
}

.online-badge {
    position: absolute;
    top: 12px;
    right: 12px;
    padding: 4px 12px;
    background: rgba(103, 194, 58, 0.9);
    color: white;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.detail-info {
    flex: 1;
}

.detail-info h3 {
    margin: 0 0 8px;
    font-size: 24px;
    color: #303133;
}

.store-storeType {
    margin: 0 0 12px;
    color: #909399;
    font-size: 14px;
}

.store-status-tags {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

.rating-display {
    display: flex;
    align-items: center;
    gap: 12px;
}

.detail-content p {
    margin: 8px 0;
    line-height: 1.8;
    color: #606266;
}

.store-description {
    margin-top: 20px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 8px;
}

.store-description p:first-child {
    margin-top: 0;
    font-weight: 500;
}

.image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 32px;
}

/* 响应式 */
@media (max-width: 1200px) {
    .stats-section {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .stats-section {
        grid-template-columns: 1fr;
    }

    .action-section {
        flex-direction: column;
        align-items: stretch;
    }

    .search-filters {
        flex-direction: column;
    }

    .search-type-select,
    .search-input,
    .filter-select {
        width: 100%;
    }
}
</style>